package com.guaju.yueshangLife.activity.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.base.BaseActivity;
import com.guaju.yueshangLife.bean.Avatar;
import com.guaju.yueshangLife.bean.MeBean;
import com.guaju.yueshangLife.bean.MeDetailBean;
import com.guaju.yueshangLife.bean.PicBean;
import com.guaju.yueshangLife.bean.UpdateMineInfo;
import com.guaju.yueshangLife.bean.UploadPicBean;
import com.guaju.yueshangLife.databinding.ActivityMyInfoBinding;
import com.guaju.yueshangLife.databinding.DialogBottomGenderBinding;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.FileUtils;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.pic.QiniuUploadHelper;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class MyInfoActivity extends BaseActivity {
    public static final int RESULT_USERNAME = 1014;
    private static final int REQUEST_PERMISSION = 1011;
    private static final int REQUEST_SELECT_IMAGES_CODE = 1012;
    private static final int REQUEST_EDIT_USERNAME = 1013;
    private static int genderFlag = -1;


    private ActivityMyInfoBinding binding;
    private Dialog genderDialog;
    private DialogBottomGenderBinding genderBinding;
    private LayoutInflater layoutInflater;
    private PicBean picBean;
    private String username;
    private String summary;
    private File file;

    @Override
    protected void loadViewLayout() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my_info);
        EventBus.getDefault().register(this);

    }

    @Override
    protected void bindViews() {
        genderDialog = new Dialog(this, R.style.BottomDialog);
        layoutInflater = LayoutInflater.from(this);
        genderBinding = DataBindingUtil.inflate(layoutInflater, R.layout.dialog_bottom_gender, null, false);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        ApiEntity.picConfig();
        ApiEntity.me();

    }

    @Override
    protected void setListener() {
        binding.rlAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photo();
            }
        });
        binding.gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showGenderDialog();
            }
        });

        binding.username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInfoActivity.this, EditUsernameActivity.class);
                intent.putExtra("username", username);
                startActivityForResult(intent, REQUEST_EDIT_USERNAME);
            }
        });
        binding.nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInfoActivity.this, EditNickNameActivity.class);
                startActivity(intent);
            }
        });
        binding.des.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInfoActivity.this, EditPersonaleInfoActivity.class);
                intent.putExtra("info", summary);
                startActivity(intent);
            }
        });
    }


    private void photo() {

        PermissionGen.with(MyInfoActivity.this)
                .addRequestCode(REQUEST_PERMISSION)
                .permissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request();

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (requestCode == REQUEST_SELECT_IMAGES_CODE) {
                if (data != null) {
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    ImageItem imageItem = images.get(0);
                    String path = imageItem.path;
                    String newPath = path;
                    if (path.contains("data/user/")) {
                        newPath = path.replace("data/user/0", "data/data");
                    }

                    File appDir = new File(Environment.getExternalStorageDirectory() + "/yslife", "avatar/");
                    if (!appDir.exists()) {
                        appDir.mkdirs();
                    }
                    String fileName = "avatar.jpg";
                    file = new File(appDir, fileName);

                    try {
                        copyFile(newPath, file.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    binding.avatar.setImageURI(file.getAbsolutePath());

                    Log.e("guajujerry", "onActivityResult: " + file.getAbsolutePath());
                    try {
                        if (picBean != null) {
                            String bucket = picBean.getBucket();
                            String name = System.currentTimeMillis() + ".jpg";
                            String token = QiniuUploadHelper.calcToken(name);
                            QiniuUploadHelper.uploadPicCanCancle(file.getAbsolutePath(), name, token);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    上传至服务器
                    ToastUtil.show("头像修改成功");
                } else {
                    Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (requestCode == REQUEST_EDIT_USERNAME) {
            if (resultCode == RESULT_USERNAME) {
                if (data != null) {
                    Bundle extras = data.getExtras();
                    String username = extras.getString(EditUsernameActivity.USERNAME);
                    binding.username.setRightTv(username);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ApiEntity.meDetail();

    }


    public static String getRealPathFromUri(Context context, Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) {
            return getRealPathFromUriAboveApi19(context, uri);
        } else {
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }

    private void showGenderDialog() {
        if (genderFlag == -1) {
            setGenderNormal();
        } else {
            if (genderFlag == 1) {
                setMaleSelected();
            } else if (genderFlag == 2) {
                setFemaleSelected();
            }
        }
        genderBinding.tvMale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setMaleSelected();
                genderDialog.dismiss();
                genderFlag = 1;
                ApiEntity.updateMineInfoSex("1");
                binding.gender.setRightTv("男");


            }
        });
        genderBinding.tvFemale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFemaleSelected();
                genderDialog.dismiss();
                genderFlag = 2;
                ApiEntity.updateMineInfoSex("2");
                binding.gender.setRightTv("女");

            }
        });
        genderBinding.llCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                genderDialog.dismiss();
            }
        });
        View contentView = genderBinding.getRoot();
        genderDialog.setContentView(genderBinding.getRoot());
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - getResources().getDimensionPixelOffset(R.dimen.dp_16);
        params.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.dp_8);
        contentView.setLayoutParams(params);
        genderDialog.setCanceledOnTouchOutside(true);
        genderDialog.getWindow().setGravity(Gravity.BOTTOM);
        genderDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        genderDialog.show();
    }

    private void setGenderNormal() {
        genderBinding.tvMale.setTextColor(getResources().getColor(R.color.grey_333));
        genderBinding.tvFemale.setTextColor(getResources().getColor(R.color.grey_333));
    }

    private void setMaleSelected() {
        genderFlag = 0;
        genderBinding.tvMale.setTextColor(getResources().getColor(R.color.colorTheme));
        genderBinding.tvFemale.setTextColor(getResources().getColor(R.color.grey_333));
    }

    private void setFemaleSelected() {
        genderFlag = 1;
        genderBinding.tvFemale.setTextColor(getResources().getColor(R.color.colorTheme));
        genderBinding.tvMale.setTextColor(getResources().getColor(R.color.grey_333));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionGen.onRequestPermissionsResult(MyInfoActivity.this, requestCode, permissions, grantResults);
    }

    @PermissionFail(requestCode = REQUEST_PERMISSION)
    public void doFailSomething() {
        Toast.makeText(this, "未开启访问相册权限", Toast.LENGTH_SHORT).show();
    }

    @PermissionSuccess(requestCode = REQUEST_PERMISSION)
    public void doSuccessThing() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_SELECT_IMAGES_CODE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPicConfig(PicBean picBean) {
        if (picBean == null) {
            ToastUtil.show("数据异常");
        } else {
            PicBean.DomainsBean domains = picBean.getDomains();
            if (domains != null) {
                String https = domains.getHttps();
            }
            String secret_key = picBean.getSecret_key();
            String access_key = picBean.getAccess_key();
            String bucket = picBean.getBucket();
            QiniuUploadHelper.init(bucket, secret_key, access_key);
            this.picBean = picBean;
            Log.e("guajujerry", "onPicConfig: " + picBean.getAccess_key() + "--" + picBean.getHotlink_prevention_key());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPicUploaded(UploadPicBean uploadPicBean) {
        if (uploadPicBean == null) {
            ToastUtil.show("数据异常");
        } else {
            String picName = uploadPicBean.getPicName();
            String avatarStr = "https://" + picBean.getDomains().getHttps() + "/" + picName;
            Log.e("guajujerry", "avatarStr: " + avatarStr);
            binding.avatar.setImageURI(avatarStr);
            PreferenceUtil.setAvatar(avatarStr);
            ApiEntity.updateMineInfoAvatar(picName);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMineInfoUpdate(UpdateMineInfo bean) {
        if (bean == null) {
            ToastUtil.show("数据异常");
        } else {
            if (bean.getCode() == 200) {
                Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MeDetailBean bean) {
        if (bean == null) return;
        MeDetailBean.DataBean data = bean.getData();
        if (data == null)
            return;
        username = data.getUsername();
        Avatar avatar = data.getAvatar();
        int group_id = data.getGroup_id();
        if (0 == group_id) {
            binding.vipCenter.setRightTv("普通会员");
            binding.vipCenter.setRightArrawVisiable(false);
        } else if (1 == group_id) {
            binding.vipCenter.setRightTv("高级会员");
            binding.vipCenter.setRightArrawVisiable(false);
        }
        binding.avatar.setImageURI(avatar.getHost() + "/" + avatar.getPath());
        binding.username.setRightTv(username);
//        binding.nickname.setRightTv(username);
        int sex = data.getSex();
        genderFlag = sex;
        if (0 == sex) {
            binding.gender.setRightTv("未设置");
//            binding.gender.setRightArrawVisiable(true);
        } else if (1 == sex) {
            binding.gender.setRightTv("男");
//            binding.gender.setRightArrawVisiable(false);
        } else if (2 == sex) {
            binding.gender.setRightTv("女");
//            binding.gender.setRightArrawVisiable(false);
        } else {
//            binding.gender.setRightArrawVisiable(true);
            binding.gender.setRightTv("未设置");
        }
        summary = data.getSummary();
        if (TextUtils.isEmpty(summary)) {
            binding.des.setRightTv("未设置");
//            binding.des.setRightArrawVisiable(true);
        } else {
            binding.des.setRightTv(summary);
//            binding.des.setRightArrawVisiable(false);
        }


        String fphone = PreferenceUtil.getFphone();
        if ((!TextUtils.isEmpty(fphone)) && fphone.length() == 11) {
            String screteTel = fphone.substring(0, 3) + "****" + fphone.substring(7, 11);
            binding.mobile.setRightTv(screteTel);
        }
        binding.mobile.setRightArrawVisiable(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MeBean bean) {
        if (bean == null) return;
        MeBean.DataBean data = bean.getData();
        if (data == null)
            return;
        String username = data.getUsername();
        binding.username.setRightTv(username);
        int group_id = data.getGroup_id();
        if (0 == group_id) {
            binding.vipCenter.setRightTv("普通会员");
        } else if (1 == group_id) {
            binding.vipCenter.setRightTv("高级会员");
        }
        Avatar avatar = data.getAvatar();
        binding.avatar.setImageURI(avatar.getHost() + "/" + avatar.getPath());
    }


    /**
     * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        return getDataColumn(context, uri, null, null);
    }

    /**
     * 适配api19及以上,根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) {
                // 使用':'分割
                String id = documentId.split(":")[1];

                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }

    /**
     * 获取数据库表中的 _data 列，即返回Uri对应的文件路径
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }


    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public void copyFile(String srcPath, String destPath) throws IOException {

        // 打开输入流
        FileInputStream fis = new FileInputStream(srcPath);
        // 打开输出流
        FileOutputStream fos = new FileOutputStream(destPath);

        // 读取和写入信息
        int len = 0;
        // 创建一个字节数组，当做缓冲区
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len);
        }

        // 关闭流  先开后关  后开先关
        fos.close(); // 后开先关
        fis.close(); // 先开后关
        binding.avatar.setImageURI(file.getAbsolutePath());
    }

}
